package com.mathlearning.auth.util;

import org.springframework.stereotype.Component;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

@Component
public class CaptchaUtil {

    private static final String CHARACTERS = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
    private static final Random random = new Random();

    public String generateCode() {
        StringBuilder code = new StringBuilder(4);
        for (int i = 0; i < 4; i++) {
            code.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length())));
        }
        return code.toString();
    }

    public String generateSvg(String code) {
        int width = 100;
        int height = 40;
        
        StringBuilder svg = new StringBuilder();
        svg.append("<svg width=\"").append(width).append("\" height=\"").append(height).append("\" xmlns=\"http://www.w3.org/2000/svg\">");
        svg.append("<rect width=\"100%\" height=\"100%\" fill=\"#f0f0f0\"/>");
        
        // 绘制噪点
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            svg.append("<circle cx=\"").append(x).append("\" cy=\"").append(y).append("\" r=\"1\" fill=\"#ccc\"/>");
        }
        
        // 绘制文字
        int fontSize = 20;
        int startX = 10;
        int startY = 30;
        
        for (int i = 0; i < code.length(); i++) {
            char ch = code.charAt(i);
            int x = startX + i * 25 + random.nextInt(5);
            int y = startY + random.nextInt(10) - 5;
            int angle = random.nextInt(20) - 10;
            
            svg.append("<text x=\"").append(x).append("\" y=\"").append(y)
               .append("\" font-size=\"").append(fontSize)
               .append("\" fill=\"#333\" transform=\"rotate(").append(angle).append(",")
               .append(x).append(",").append(y).append(")\">")
               .append(ch).append("</text>");
        }
        
        // 绘制干扰线
        for (int i = 0; i < 3; i++) {
            svg.append("<line x1=\"").append(random.nextInt(width))
               .append("\" y1=\"").append(random.nextInt(height))
               .append("\" x2=\"").append(random.nextInt(width))
               .append("\" y2=\"").append(random.nextInt(height))
               .append("\" stroke=\"#ccc\" stroke-width=\"1\"/>");
        }
        
        svg.append("</svg>");
        return svg.toString();
    }
}










